# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   ApiTest
# FileName:      request_method.py
# Author:       liu
# Datetime:     2024/9/7 下午4:40
# Description: 根据媒体请求类型的不同，返回不同的请求结果
# ---------------------------------------------------------------------------
import requests


class RequestsMethod:
    def __init__(self):
        # 获取认证
        login_host = 'http://36.139.193.99:8088/auth'
        login_data = {
            "username": "admin",
            "password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="
        }
        self.req_session = requests.Session()
        res = self.req_session.request(url=login_host, json=login_data, method='post')
        token = res.json().get('token')
        self.req_session.headers["Authorization"] = f"Bearer {token}"

    def request_all(self, url, req_method, req_type, case_data):
        if req_type == 'application/json' or req_type == 'json':
            return self.req_session.request(url=url, json=case_data, method=req_method)
        elif req_type == "application/x-www-form-urlencoded" or req_type == "form":
            return self.req_session.request(url=url, data=case_data, method=req_method)
        elif req_type == "multipart/form-data" or req_type == "form-data":
            return self.req_session.request(url=url, files=case_data, method=req_method)
        elif req_type == 'query' or req_type == 'params':
            return self.req_session.request(url=url, params=case_data, method=req_method)
        elif req_type is None:
            return self.req_session.request(url=url, method=req_method)
            # 判断媒体类型是否为query|json或者为json|query, 表示请求体和地址栏同时传参
        elif req_type == "query|json" or req_type == "json|query":
            # requests是支持地址栏和请求体同时传参的。地址栏使用params传参，请求体根据不同的媒体类型选择不同的关键字传参。
            return self.req_session.request(method=req_method, url=url, params=case_data["query"],
                                            json=case_data["body"])
        else:
            return self.req_session.request(url=url, data=case_data, method=req_method)


if __name__ == '__main__':
    req = RequestsMethod()